"""
在未排序的数组中找到第 k 个最大的元素。请注意，你需要找的是数组排序后的第 k 个最大的元素，而不是第 k 个不同的元素。

示例 1:

输入: [3,2,1,5,6,4] 和 k = 2
输出: 5
示例 2:

输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
输出: 4
说明:

你可以假设 k 总是有效的，且 1 ≤ k ≤ 数组的长度。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/kth-largest-element-in-an-array
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
from typing import List


class Solution:
    # 快排(超时)
    def findKthLargest(self, nums: List[int], k: int) -> int:
        self.quick_sort(nums, 0, len(nums) - 1)
        return nums[-k]

    def quick_sort(self, nums: List[int], start: int, end: int) -> None:
        for i in range(end):
            if nums[i] <= nums[i + 1]:
                start = i
            else:
                break

        if start < end:
            p = self.partition(nums, start, end)
            self.quick_sort(nums, start, p - 1)
            self.quick_sort(nums, p + 1, end)

    def partition(self, nums: List[int], start: int, end: int) -> int:
        i = start - 1
        p = nums[end]
        for j in range(start, end):
            if nums[j] <= p:
                i = i + 1
                nums[i], nums[j] = nums[j], nums[i]
        nums[i + 1], nums[end] = nums[end], nums[i + 1]
        return i + 1

    def findKthLargest2(self, nums: List[int], k: int) -> int:
        import heapq
        heap = []
        heapq.heapify(heap)
        for num in nums:
            heapq.heappush(heap, num)
            if len(heap) > k:
                heapq.heappop(heap)
        return heap[0]


if __name__ == '__main__':
    arr = [3,2,3,1,2,4,5,5,6]
    s = Solution()
    print(arr)
    print(s.findKthLargest(arr, 4))
